package lc20240514;

import java.util.ArrayList;

//从上到下打印二叉树
public class Demo2 {
    public static void main(String[] args) {

        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = null;
        root.left.left = new TreeNode(4);
        root.left.right = null;

        ArrayList<Integer> result = PrintFromTopToBottom(root);

        for (Integer in : result) {
            System.out.println(in);
        }
    }
    public static ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<ArrayList<Integer>> levels = new ArrayList<>();
        traverseTree(root, 0, levels);

        ArrayList<Integer> result = new ArrayList<>();
        for (ArrayList<Integer> level : levels) {
            for (Integer nodeVal : level) {
                if (nodeVal != null) {
                    result.add(nodeVal);
                }
            }
        }
        return result;
    }

    private static void traverseTree(TreeNode node, int level, ArrayList<ArrayList<Integer>> levels) {
        if (node == null) {
            return;
        }

        if (levels.size() == level) {
            levels.add(new ArrayList<>());
        }

        levels.get(level).add(node.val);

        traverseTree(node.left, level + 1, levels);
        traverseTree(node.right, level + 1, levels);
    }
}